-- vector.lua
-- 二维向量工具类：提供向量运算功能

local Vector2 = {}
Vector2.__index = Vector2

-- 构造函数：创建新的二维向量
function Vector2.new(x, y)
    return setmetatable({x = x or 0, y = y or 0}, Vector2)
end

-- 向量加法
function Vector2:add(other)
    return Vector2.new(self.x + other.x, self.y + other.y)
end

-- 向量减法
function Vector2:subtract(other)
    return Vector2.new(self.x - other.x, self.y - other.y)
end

-- 向量标量乘法
function Vector2:multiply(scalar)
    return Vector2.new(self.x * scalar, self.y * scalar)
end

-- 计算向量长度
function Vector2:length()
    return math.sqrt(self.x * self.x + self.y * self.y)
end

-- 向量归一化
function Vector2:normalize()
    local len = self:length()
    if len > 0 then
        return Vector2.new(self.x / len, self.y / len)
    end
    return Vector2.new(0, 0)
end

-- 计算两点间距离
function Vector2:distance(other)
    return math.sqrt((self.x - other.x)^2 + (self.y - other.y)^2)
end

-- 点积
function Vector2:dot(other)
    return self.x * other.x + self.y * other.y
end

-- 判断是否为零向量
function Vector2:isZero()
    return self.x == 0 and self.y == 0
end

-- 克隆向量
function Vector2:clone()
    return Vector2.new(self.x, self.y)
end

-- 设置向量值
function Vector2:set(x, y)
    self.x = x or self.x
    self.y = y or self.y
    return self
end

-- 转换为字符串
function Vector2:toString()
    return string.format("Vector2(%.2f, %.2f)", self.x, self.y)
end

-- 常用常量
Vector2.zero = Vector2.new(0, 0)
Vector2.one = Vector2.new(1, 1)
Vector2.up = Vector2.new(0, 1)
Vector2.down = Vector2.new(0, -1)
Vector2.left = Vector2.new(-1, 0)
Vector2.right = Vector2.new(1, 0)

return Vector2